package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import com.itheima.util.DateUtils;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;
    @Reference
    private SetmealService setmealService;
    @Reference
    private ReportService reportService;

    //会员数量折线图数据
    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {
        Map<String, Object> map = new HashMap<>();
        List<String> months = new ArrayList();
        Calendar calendar = Calendar.getInstance();//获得日历对象，模拟时间就是当前时间
        //计算过去一年的12个月
        calendar.add(Calendar.MONTH, -12);//获得当前时间往前推12个月的时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy.MM");
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);//获得当前时间往后推一个月日期
            Date date = calendar.getTime();
            months.add(format.format(date));
        }
        map.put("months", months);
        List<Integer> memberCount = memberService.findMemberCountByMonths(months);
        map.put("memberCount", memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }

    //套餐预约占比饼形图
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {
        try {
            //饼形图所需要的json格式数据
            Map<String, Object> data = new HashMap<>();
            //查询套餐集合
            List<Map<String, Object>> setmealCount = setmealService.findSetmealCount();
            //将套餐添加到
            data.put("setmealCount", setmealCount);
            List<String> setmealNames = new ArrayList<>();
            for (Map<String, Object> map : setmealCount) {
                String name = (String) map.get("name");
                setmealNames.add(name);
            }
            data.put("setmealNames", setmealNames);
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }


    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> data = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, data);
        } catch (Exception e) {
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //excel报表导出
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> result = reportService.getBusinessReportData();
            //取出返回结果数据，准备将报表数据写入到Excel文件中
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
            //读取模板文件的绝对路径
            String filePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
            //基于提供的Excel模板文件在内存中创建一个Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            //读取第一个工作表
            XSSFSheet sheet = excel.getSheetAt(0);
            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);//日期

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);//总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int rowNum = 12;
            for (Map map : hotSetmeal) {//热门套餐
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                String remark = (String) map.get("remark");
                row = sheet.getRow(rowNum++);
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比
                row.getCell(7).setCellValue(remark);//备注
            }
            //使用输出流进行表格下载,基于浏览器作为客户端下载
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");//指定以附件形式进行下载
            excel.write(out);
            out.flush();
            out.close();
            excel.close();
            return null;
        } catch (Exception e) {
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }

    }

    //导出运营数据到PDF文件并提供客户端下载
    @RequestMapping("/exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> result = reportService.getBusinessReportData();
            //取出返回结果数据，准备将报表数据写入到Excel文件中
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
            //动态获取pdf模板文件绝对磁盘路径
            String jrxmlPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jrxml";
            String jasperPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jasper";
            //编译模板
            JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);
            //填充数据---使用JavaBean数据源方式填充
            JasperPrint jasperPrint =
                    JasperFillManager.fillReport(jasperPath, result,
                            new JRBeanCollectionDataSource(hotSetmeal));

            //创建输出流，用于从服务器写数据到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/pdf");
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");
            //输出文件
            JasperExportManager.exportReportToPdfStream(jasperPrint, out);
            out.flush();
            out.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //年龄分布
    @RequestMapping("/findByAge")
    public Result findByAge() throws Exception {
        List<Integer> ages = new ArrayList<>();
        //设置计数器，计算各个年龄段的数量
        //0-6为婴幼儿
        int yy = 0;
        //7-12为少儿、
        int sn = 0;
        //13-17岁为青少年
        int qsn = 0;
        //18-45岁为青年、
        int qn = 0;
        //46-69岁为中年、
        int zn = 0;
        //>69岁为老年
        int ln = 0;

        //查询所有会员出生日期
        List<String> birthdays = reportService.findByBirthdays();
        //遍历所有日期
        for (String birthday : birthdays) {
            //将String类型转成Date类型
            Date bt1 = DateUtils.parseString2Date(birthday);
            //使用工具类计算出对应出生日期的年龄
            int age = DateUtils.getAge(bt1);
            //判断年龄的范围
            if (age <= 6) {
                yy += 1;
            } else if (age >= 7 && age <= 12) {
                sn += 1;
            } else if (age >= 13 && age <= 17) {
                qsn += 1;
            } else if (age >= 18 && age <= 45) {
                qn += 1;
            } else if (age >= 46 && age <= 69) {
                zn += 1;
            } else {
                ln += 1;
            }
        }
        Collections.addAll(ages, yy, sn, qsn, qn, zn, ln);
        return new Result(true, "年龄分布查询成功", ages);
    }

    /**
     * 数量折线图数据
     * @param value1
     * @return
     */
    @RequestMapping("/getMemberReportDate")
    public Result getMemberReportDate(String value1) {
        try {
            String[] split = value1.split(",");
            //取出开始和结束时间
            Date sd = DateUtils.parseString2Date(split[0]);
            Date ed = DateUtils.parseString2Date(split[1]);
            //获取当天时间
            Date today = new Date();
            if (sd.getTime() > today.getTime() || ed.getTime() > today.getTime()) {
                String over = "timeTOtoday";
                return new Result(false, "未来不可预测");
            }

            //拿到每天的日期
            ArrayList<String> dayList = DateUtils.findDaysStr(split[0], split[1]);

            Map<String, Object> map = findOrders(dayList);

            map.put("dayList", dayList);

            return new Result(true, "到诊人数和预约人数查询成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, "到诊人数和预约人数查询失败");
        }
    }

    //获取本周时间区域内到诊人数和预约人数
    @RequestMapping("/getMemberReportCount")
    public Result getMemberReportCount() throws Exception {
        try {

            //使用工具类找到当前时间前一周内每天的时间日期
            ArrayList<String> dayList = DateUtils.findDaysToWeek();


            Map<String, Object> map = findOrders(dayList);

            map.put("dayList", dayList);


            return new Result(true, "到诊人数和预约人数查询成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, "到诊人数和预约人数查询失败");
        }
    }

    public Map<String, Object> findOrders(ArrayList<String> dayList) {
        Map<String, Object> map = new HashMap<>();

        //查询预约数量
        List<Integer> orderStatus = reportService.findtoOrderStatus(dayList);
        map.put("orderStatus", orderStatus);

        //查询到诊数量
        List<Integer> orderList = reportService.findtoOrderList(dayList);
        map.put("orderList", orderList);
        return map;
    }

    //一周内体检收入统计
    @RequestMapping("getSetmealReportMoney")
    public Result getSetmealReportMoney() {
        try {
            //使用工具类找到当前时间前一周内每天的时间日期
            ArrayList<String> dayList = DateUtils.findDaysToWeek();

            List<String> names = reportService.findSetmealNameCount();   //套餐名称组

            Map<String, Object> date = setmealMoneyToDate(names, dayList);


            return new Result(true, "体检收入统计查询成功", date);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, "体检收入统计查询失败");
        }
    }

    //给定时间内体检收入统计
    @RequestMapping("/getSetmealReportMoneyDate")
    public Result findOrderDate( String value1) {
        try {
            String[] split = value1.split(",");
            //拿到每天的日期
            ArrayList<String> dayList = DateUtils.findDaysStr(split[0], split[1]);

            //取出开始和结束时间
            Date sd = DateUtils.parseString2Date(split[0]);
            Date ed = DateUtils.parseString2Date(split[1]);
            //获取当天时间
            Date today = new Date();
            if (sd.getTime() > today.getTime() || ed.getTime() > today.getTime()) {
                String over = "timeTOtoday";
                return new Result(false, "不可预测");
            }

            List<String> names = reportService.findSetmealNameCount();   //套餐名称组

            Map<String, Object> date = setmealMoneyToDate(names, dayList);

            return new Result(true, "体检收入统计查询成功", date);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, "体检收入统计查询失败");
        }
    }

    /**
     * 获取套餐在区域时间内的金额
     *
     * @param names   所有套餐名
     * @param dayList 区域时间
     * @return 对应套餐在区域时间内的总金额
     */
    public Map<String, Object> setmealMoneyToDate(List<String> names, ArrayList<String> dayList) {
        Map<String, Object> date = new HashMap();

        List<Map<String, Object>> moneys = new ArrayList<>();

        double sum = 0.0;
        //找到每个套餐名
        for (String name : names) {
            //找到每个套餐的id
            Integer id = reportService.findnameById(name);
            //当前套餐的金额
            Integer money = reportService.findSetmealMoney(id);
            //查到当前套餐在时间内的数量
            Double num = reportService.findSetmealNum(id, dayList);
            Map<String, Object> map = new HashMap<>();
            //当前套餐在时间内的金额
            double znum = money * num;
            sum += znum;
            if (znum > 0){
                map.put("name", name);
                map.put("value", znum);
                moneys.add(map);
            }
        }
        Map<String, Object> map = new HashMap<>();
        //最后将总收入放到集合中
        names.add("总收入");
        map.put("name", "总收入");
        map.put("value", sum);
        moneys.add(map);

        date.put("moneys", moneys);
        date.put("names", names);
        return date;
    }
}
